<template>
    <view class="travel-recommend">
        <view class="recommend-header">
            <view class="header-left">
                <text class="recommend-title">近日游玩推荐</text>
            </view>
            <view class="header-right" @click="showDatePicker = true">
                <text class="date-icon">📅</text>
                <text class="date-text">{{ dateRangeText }}</text>
            </view>
        </view>
        
        <!-- 日期选择器 -->
        <view v-if="showDatePicker" class="date-picker-overlay" @click.stop="showDatePicker = false">
            <view class="date-picker-container" @click.stop>
                <view class="date-picker-header">
                    <text class="date-picker-title">选择出行时间</text>
                    <text class="date-picker-close" @click="showDatePicker = false">×</text>
                </view>
                <view class="date-picker-content">
                    <picker-view class="picker-view" :value="pickerValue" @change="onDateChange">
                        <picker-view-column>
                            <view class="picker-item" v-for="(item, index) in startOptions" :key="'start-'+index">{{ item }}</view>
                        </picker-view-column>
                        <picker-view-column>
                            <view class="picker-item">至</view>
                        </picker-view-column>
                        <picker-view-column>
                            <view class="picker-item" v-for="(item, index) in endOptions" :key="'end-'+index">{{ item }}</view>
                        </picker-view-column>
                    </picker-view>
                </view>
                <view class="date-picker-footer">
                    <view class="date-picker-btn cancel-btn" @click="showDatePicker = false">取消</view>
                    <view class="date-picker-btn confirm-btn" @click="confirmDateRange">确定</view>
                </view>
            </view>
        </view>
        
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <view class="loading-content">
                <text class="loading-icon">🔄</text>
                <text class="loading-text">正在获取AI推荐...</text>
            </view>
        </view>
        
        <!-- 错误状态 -->
        <view v-if="error" class="error-state">
            <view class="error-content">
                <text class="error-icon">⚠️</text>
                <text class="error-text">{{ error }}</text>
                <view class="retry-btn" @click="getRecommendation">重试</view>
            </view>
        </view>
        
        <!-- 推荐内容 -->
        <view v-if="!loading && !error && recommendList" class="recommend-content">
            <view class="content-header">
                <text class="content-title">AI智能推荐</text>
                <text class="content-subtitle">{{ startDate && endDate ? `${startDate} 到 ${endDate}` : '根据当地天气为您定制' }}</text>
            </view>
            <view class="content-body">
                <view class="formatted-content" v-if="isFormattedText">
                    <view class="recommendation-title">
                        <text>{{ formattedTitle }}</text>
                    </view>
                    
                    <view class="recommendation-date" v-if="formattedDate">
                        <text class="section-title">旅行日期</text>
                        <text class="section-content">{{ formattedDate }}</text>
                    </view>
                    
                    <view class="recommendation-weather" v-if="formattedWeather.length > 0">
                        <text class="section-title">天气情况</text>
                        <view class="weather-list">
                            <view class="weather-item" v-for="(item, index) in formattedWeather" :key="index">
                                <text>{{ item }}</text>
                            </view>
                        </view>
                    </view>
                    
                    <view class="recommendation-tips" v-if="formattedTips">
                        <text class="section-title">行程安排</text>
                        <text class="section-content">{{ formattedTips }}</text>
                    </view>
                    
                    <view class="recommendation-schedule" v-if="formattedSchedule.length > 0">
                        <view class="day-schedule" v-for="(day, dayIndex) in formattedSchedule" :key="dayIndex">
                            <text class="day-title">{{ day.title }}</text>
                            
                            <view class="time-slots">
                                <view class="time-slot" v-for="(slot, slotIndex) in day.slots" :key="slotIndex">
                                    <text class="time-range">{{ slot.time }}</text>
                                    <text class="time-activity">{{ slot.activity }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    
                    <!-- 按钮区域 -->
                    <view class="action-buttons">
                        <view class="regenerate-btn" @click="() => getRecommendation(true)">
                            <text class="map-icon">🔄</text>
                            <text class="map-text">重新生成旅游攻略</text>
                        </view>
                        <view class="save-plan-btn" @click="saveToPlan">
                            <text class="save-icon">💾</text>
                            <text class="save-text">保存为行程</text>
                        </view>
                    </view>
                </view>
                <text v-else class="recommend-text">{{ recommendList }}</text>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineExpose, computed, watch } from 'vue';
import { getAiResponse } from '@/api/ai';
import { getLastLocation } from '@/api/location';
import { getIpLocation } from '@/api/GaoDeApi';
import { getUserTravelPlans, createTravelPlan, updateTravelPlan } from '@/api/plan';
const recommendList = ref('');
const loading = ref(false);
const error = ref('');
const currentCity = ref(null);
const weatherData = ref(null);
const lastMessage = ref('');
const messageCache = ref({});

// 格式化后的内容
const formattedTitle = ref('');
const formattedDate = ref('');
const formattedWeather = ref([]);
const formattedTips = ref('');
const formattedSchedule = ref([]);
const isFormattedText = ref(false);

// 日期选择器相关
const showDatePicker = ref(false);
const startDate = ref('');
const endDate = ref('');
const pickerValue = ref([0, 0, 0]);

// 生成日期选项，从今天开始的30天
const generateDateOptions = (days) => {
    const options = [];
    const today = new Date();
    
    for (let i = 0; i < days; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        options.push(`${month}月${day}日`);
    }
    
    return options;
};

const startOptions = generateDateOptions(30);
const endOptions = computed(() => {
    const startIndex = pickerValue.value[0];
    return startOptions.slice(startIndex);
});

// 日期范围文本
const dateRangeText = computed(() => {
    if (startDate.value && endDate.value) {
        return `${startDate.value}至${endDate.value}`;
    }
    return '选择出行时间';
});

// 处理日期选择变化
const onDateChange = (e) => {
    const values = e.detail.value;
    // 确保结束日期不早于开始日期
    if (values[0] > values[2]) {
        values[2] = values[0];
    }
    pickerValue.value = values;
};

// 确认日期范围
const confirmDateRange = () => {
    startDate.value = startOptions[pickerValue.value[0]];
    endDate.value = endOptions.value[pickerValue.value[2]];
    showDatePicker.value = false;
    getRecommendation();
};

// 格式化天气信息
const formatWeatherInfo = (forecastData) => {
    if (!forecastData || !forecastData.length) return '';
    
    return forecastData.slice(0, 3).map(item => {
        const date = new Date(item.date);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${month}月${day}日：${item.dayweather}，温度${item.nighttemp}℃-${item.daytemp}℃`;
    });
};

// 获取当前定位城市
const getCurrentLocation = async () => {
    try {
        const res = await getIpLocation();
        if (res.data) {
            currentCity.value = res.data.city;
            return true;
        }
        return false;
    } catch (err) {
        console.error('获取当前定位失败:', err);
        return false;
    }
};

// 缓存相关处理
const CACHE_EXPIRATION = 3 * 60 * 60 * 1000; // 3小时过期时间(毫秒)

// 检查缓存是否有效
const isCacheValid = (timestamp) => {
    if (!timestamp) return false;
    const now = new Date().getTime();
    return (now - timestamp) < CACHE_EXPIRATION;
};

// 保存缓存，包含时间戳
const saveCache = (cache) => {
    try {
        const cacheData = {
            data: cache,
            timestamp: new Date().getTime()
        };
        uni.setStorageSync('recommendCache', JSON.stringify(cacheData));
    } catch (e) {
        console.error('保存缓存失败:', e);
    }
};

// 初始化数据
const initializeData = async () => {
    try {
        const userInfo = uni.getStorageSync('userInfo');
        const locationRes = await getLastLocation(userInfo.id);
        
        // 如果没有获取到最后选择的城市，尝试使用当前定位城市
        if (!locationRes.data) {
            const gotLocation = await getCurrentLocation();
            if (!gotLocation) {
                error.value = '无法获取城市信息';
                return;
            }
        } else {
            currentCity.value = locationRes.data.city;
        }

        // 设置默认日期范围为今天和明天
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        
        startDate.value = `${today.getMonth() + 1}月${today.getDate()}日`;
        endDate.value = `${tomorrow.getMonth() + 1}月${tomorrow.getDate()}日`;

        // 尝试从本地存储加载缓存
        try {
            const cachedData = uni.getStorageSync('recommendCache');
            if (cachedData) {
                const parsedCache = JSON.parse(cachedData);
                // 检查缓存是否在有效期内
                if (isCacheValid(parsedCache.timestamp)) {
                    messageCache.value = parsedCache.data;
                } else {
                    // 缓存已过期，清除
                    messageCache.value = {};
                    uni.removeStorageSync('recommendCache');
                }
            }
        } catch (e) {
            console.error('加载缓存失败:', e);
        }

        // 等待天气数据更新后再获取推荐
        const weatherUpdatePromise = new Promise((resolve) => {
            const weatherListener = (data) => {
                weatherData.value = data;
                uni.$off('weather-updated', weatherListener);
                resolve();
            };
            uni.$on('weather-updated', weatherListener);
        });
        
        // 设置超时，避免无限等待
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => reject(new Error('等待天气数据超时')), 5000);
        });
        
        try {
            await Promise.race([weatherUpdatePromise, timeoutPromise]);
            await getRecommendation();
        } catch (err) {
            console.error('获取天气数据超时，使用默认推荐');
            await getRecommendation();
        }
    } catch (err) {
        console.error('初始化数据失败:', err);
        error.value = '初始化失败，请稍后重试';
    }
};

// 计算日期之间的天数
const calculateDays = (start, end) => {
    try {
        const startDate = new Date(start.year, start.month - 1, start.day);
        const endDate = new Date(end.year, end.month - 1, end.day);
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        // 由于包含起始日期，所以需要加1
        return diffDays + 1;
    } catch (error) {
        console.error('计算天数出错:', error);
        return 1; // 出错时返回默认值1
    }
};

// 构建推荐请求消息
const buildRequestMessage = () => {
    let dateInfo = '';
    let weatherText = '';
    let daysCount = 1; // 设置默认值为1天
    
    if (startDate.value && endDate.value) {
        // 验证日期的有效性
        const start = parseChineseDate(startDate.value);
        const end = parseChineseDate(endDate.value);
        
        if (start && end) {
            dateInfo = `，计划${startDate.value}至${endDate.value}期间出行`;
            
            // 修正计算天数的方法
            daysCount = calculateDays({
                year: start.getFullYear(),
                month: start.getMonth() + 1,
                day: start.getDate()
            }, {
                year: end.getFullYear(),
                month: end.getMonth() + 1,
                day: end.getDate()
            });
            
            // 确保天数至少为1天
            daysCount = Math.max(1, daysCount);
            
            // 根据选择的天数获取对应的天气信息
            if (weatherData.value) {
                const weatherInfo = formatWeatherInfo(weatherData.value)
                    .slice(0, daysCount);
                if (weatherInfo.length > 0) {
                    weatherText = `，这${daysCount}天的天气为：\n${weatherInfo.join('\n')}`;
                }
            }
        } else {
            // 如果日期无效，重置日期选择
            resetDateRange();
            return null;
        }
    }
    
    // 确保返回消息中包含正确的天数
    return `我想去${currentCity.value}旅游${dateInfo}${weatherText}，请帮我生成一份${daysCount}天的旅游攻略，包含每天的具体行程安排，每天的行程要包含景点的游玩时间`;
};

// 解析中文日期格式（如：3月31日）
const parseChineseDate = (dateStr) => {
    if (!dateStr) return null;
    const matches = dateStr.match(/(\d+)月(\d+)日/);
    if (!matches) return null;
    
    const currentYear = new Date().getFullYear();
    const month = parseInt(matches[1]) - 1; // 月份从0开始
    const day = parseInt(matches[2]);
    
    const date = new Date(currentYear, month, day);
    return date;
};

// 重置日期范围为默认值
const resetDateRange = () => {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    startDate.value = `${today.getMonth() + 1}月${today.getDate()}日`;
    endDate.value = `${tomorrow.getMonth() + 1}月${tomorrow.getDate()}日`;
    
    // 重置选择器值
    pickerValue.value = [0, 0, 0];
};

// 生成行程标题
const generatePlanTitle = () => {
    if (!currentCity.value || !startDate.value || !endDate.value) return '';
    return `${currentCity.value}${startDate.value}至${endDate.value}旅游攻略`;
};

// 保存为行程
const saveToPlan = async () => {
    if (!recommendList.value) {
        uni.showToast({
            title: '暂无可保存的行程内容',
            icon: 'none'
        });
        return;
    }
    
    const planTitle = generatePlanTitle();
    const userInfo = uni.getStorageSync('userInfo');
    
    if (!userInfo || !userInfo.id) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        });
        return;
    }
    
    try {
        // 检查是否存在同名行程
        const existingPlans = await getUserTravelPlans(userInfo.id);
        const existingPlan = existingPlans.data.find(plan => plan.planName === planTitle);
        
        if (existingPlan) {
            // 显示确认对话框
            uni.showModal({
                title: '提示',
                content: '已存在同名行程，请选择操作',
                showCancel: true,
                cancelText: '新增',
                confirmText: '覆盖',
                success: async (res) => {
                    if (res.confirm) {
                        // 覆盖现有行程
                        await updateTravelPlan(existingPlan.id, {
                            planName: planTitle,
                            travelPlan: recommendList.value,
                            userId: userInfo.id
                        });
                        uni.showToast({
                            title: '行程已更新',
                            icon: 'success'
                        });
                    } else {
                        // 创建新行程（使用递增数字后缀）
                        const newTitle = `${planTitle}(${existingPlans.data.filter(p => p.planName.startsWith(planTitle)).length + 1})`;
                        await createTravelPlan({
                            planName: newTitle,
                            travelPlan: recommendList.value,
                            userId: userInfo.id
                        });
                        uni.showToast({
                            title: '新行程已创建',
                            icon: 'success'
                        });
                    }
                }
            });
        } else {
            // 直接创建新行程
            await createTravelPlan({
                planName: planTitle,
                travelPlan: recommendList.value,
                userId: userInfo.id
            });
            uni.showToast({
                title: '行程已保存',
                icon: 'success'
            });
        }
    } catch (err) {
        console.error('保存行程失败:', err);
        uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
        });
    }
};

// 格式化推荐内容
const formatRecommendContent = (text) => {
    try {
        // 重置格式化数据
        formattedTitle.value = '';
        formattedDate.value = '';
        formattedWeather.value = [];
        formattedTips.value = '';
        formattedSchedule.value = [];
        
        // 首先清理文本中的所有**符号
        text = text.replace(/\*\*/g, '');
        
        // 设置日期范围
        if (startDate.value && endDate.value) {
            formattedDate.value = `${startDate.value} 至 ${endDate.value}`;
        }
        
        // 处理天气信息
        if (weatherData.value) {
            const start = parseChineseDate(startDate.value);
            const end = parseChineseDate(endDate.value);
            if (start && end) {
                const daysCount = calculateDays({
                    year: start.getFullYear(),
                    month: start.getMonth() + 1,
                    day: start.getDate()
                }, {
                    year: end.getFullYear(),
                    month: end.getMonth() + 1,
                    day: end.getDate()
                });
                
                formattedWeather.value = weatherData.value
                    .slice(0, daysCount)
                    .map(item => {
                        const date = new Date(item.date);
                        const month = date.getMonth() + 1;
                        const day = date.getDate();
                        return `${month}月${day}日: ${item.dayweather}，温度${item.nighttemp}℃-${item.daytemp}℃`;
                    });
            }
        }
        
        // 提取并处理行程安排
        const scheduleMatches = text.matchAll(/第([一二三四五六七八九十\d]+)[天日][\s\S]*?(?=第[一二三四五六七八九十\d]+[天日]|$)/g);
        const schedules = Array.from(scheduleMatches);
        
        schedules.forEach((match, index) => {
            const dayContent = match[0];
            const dayNumber = match[1];
            
            // 计算当前日期
            const start = parseChineseDate(startDate.value);
            if (start) {
                const currentDate = new Date(start);
                currentDate.setDate(start.getDate() + index);
                const month = currentDate.getMonth() + 1;
                const day = currentDate.getDate();
                
                const dayTitle = `第${dayNumber}天: ${month}月${day}日`;
                
                const timeSlots = [];
                // 修改时间段匹配正则，不再包含**的匹配
                const timeMatches = dayContent.matchAll(/([上中下晚]午|早晨|傍晚|晚上)[:：]([\s\S]*?)(?=[上中下晚]午|早晨|傍晚|晚上|$)/g);
                
                for (const timeMatch of timeMatches) {
                    const timeSlot = timeMatch[1];
                    const activities = timeMatch[2].trim()
                        .split(/\d+[\.。、]/)
                        .filter(activity => activity.trim())
                        .map(activity => activity.trim());
                    
                    activities.forEach(activity => {
                        if (activity) {
                            timeSlots.push({
                                time: timeSlot,
                                activity: activity
                            });
                        }
                    });
                }
                
                if (timeSlots.length > 0) {
                    formattedSchedule.value.push({
                        title: dayTitle,
                        slots: timeSlots
                    });
                }
            }
        });
        
        isFormattedText.value = true;
    } catch (err) {
        console.error('格式化推荐内容失败:', err);
        isFormattedText.value = false;
    }
};

// 获取AI推荐
const getRecommendation = async (ignoreCache = false) => {
    if (!currentCity.value) {
        error.value = '请先选择城市';
        return;
    }
    
    const message = buildRequestMessage();
    
    // 检查缓存中是否有相同请求的结果，除非明确要求忽略缓存
    if (!ignoreCache && messageCache.value[message]) {
        console.log('使用缓存的推荐结果');
        recommendList.value = messageCache.value[message];
        formatRecommendContent(recommendList.value);
        return;
    }
    
    loading.value = true;
    error.value = '';
    lastMessage.value = message;
    
    try {
        const response = await getAiResponse(message);
        
        if (response.success) {
            recommendList.value = response.data;
            formatRecommendContent(recommendList.value);
            
            // 存入缓存
            messageCache.value[message] = response.data;
            
            // 更新本地存储，包含时间戳
            saveCache(messageCache.value);
        } else {
            error.value = response.error || '获取推荐失败';
        }
    } catch (err) {
        error.value = '获取推荐时发生错误';
        console.error('获取AI推荐失败:', err);
    } finally {
        loading.value = false;
    }
};

// 监听城市选择事件和天气数据
onMounted(() => {
    // 初始化数据
    initializeData();
    
    // 监听城市选择事件
    uni.$on('city-selected', (city) => {
        currentCity.value = city.city;
        getRecommendation();
    });
    
    // 监听天气更新事件
    uni.$on('weather-updated', (data) => {
        weatherData.value = data;
        if (currentCity.value) {
            getRecommendation();
        }
    });
});

// 组件卸载时清理事件监听
onUnmounted(() => {
    uni.$off('city-selected');
    uni.$off('weather-updated');
});

// 暴露方法供父组件调用
defineExpose({
    getRecommendation
});

// 生成旅游路线图
const generateRouteMap = async () => {
    // 显示生成中动画
    uni.showLoading({
        title: '路线生成中...',
        mask: true
    });
    
    // 使用AI接口获取景点信息
    const message = recommendList.value + '根据上述信息帮我提取景点名称';
    
    try {
        const aidata = await getAiResponse(message);
        
        // 隐藏加载动画
        uni.hideLoading();
        
        if (!aidata.success || !aidata.data) {
            uni.showToast({
                title: '提取景点失败',
                icon: 'none'
            });
            return;
        }
        
        // 解析AI返回的景点数据 - 新增支持多种格式
        let attractions = [];
        
        // 尝试匹配以数字开头的列表格式 (如 "1. 景点名称")
        const numberedMatches = aidata.data.match(/\d+\.\s*([^\n]+)/g);
        if (numberedMatches && numberedMatches.length > 0) {
            attractions = numberedMatches.map(line => ({
                name: line.replace(/^\d+\.\s*/, '').trim(),
                description: '景点'
            }));
        } else {
            // 尝试匹配以破折号开头的列表格式 (如 "- 景点名称")
            attractions = aidata.data.split('\n')
                .filter(line => line.trim() && (line.startsWith('-') || line.startsWith('•')))
                .map(line => ({
                    name: line.replace(/^[-•]\s*/, '').trim(),
                    description: '景点'
                }));
        }
        
        // 如果上述都没匹配到，尝试直接提取可能的景点名称
        if (attractions.length === 0) {
            const lines = aidata.data.split('\n');
            for (const line of lines) {
                const trimmedLine = line.trim();
                if (trimmedLine && trimmedLine.length > 2 && 
                    !trimmedLine.includes('景点名称') && 
                    !trimmedLine.includes('以下是') && 
                    !trimmedLine.includes('提取') &&
                    trimmedLine.length < 30) {
                    attractions.push({
                        name: trimmedLine,
                        description: '景点'
                    });
                }
            }
        }
            
        if (attractions.length === 0) {
            uni.showToast({
                title: '未找到景点信息',
                icon: 'none'
            });
            return;
        }
        
        console.log('提取到的景点:', attractions);
        
        // 从行程内容中提取城市名称
        let city = currentCity.value;
        
        // 将景点数据保存到本地存储
        const travelData = {
            city: city,
            title: formattedTitle.value || '旅游路线图',
            dateRange: dateRangeText.value !== '选择出行时间' ? dateRangeText.value : `${startDate.value}至${endDate.value}`,
            attractions: attractions,
            timestamp: new Date().getTime()
        };
        
        try {
            // 使用临时存储保存数据
            uni.setStorageSync('travelRouteData', JSON.stringify(travelData));
            
            // 跳转到旅游路线图页面
            uni.navigateTo({
                url: '/package-discovery/pages/AI-travel',
                success: function() {
                    console.log('页面跳转成功');
                },
                fail: function(err) {
                    console.error('页面跳转失败:', err);
                    uni.showToast({
                        title: '页面跳转失败',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        } catch (e) {
            console.error('保存数据失败:', e);
            uni.showToast({
                title: '数据处理失败',
                icon: 'none',
                duration: 2000
            });
        }
    } catch (error) {
        // 隐藏加载动画
        uni.hideLoading();
        console.error('获取景点信息失败:', error);
        uni.showToast({
            title: '获取景点信息失败',
            icon: 'none'
        });
    }
};

</script>

<style scoped lang="scss">
// 颜色变量
$background-color: #f9f9f9;
$card-background: #ffffff;
$text-primary: #000000;
$text-secondary: #666666;
$accent-color: #007aff;
$card-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
$error-color: #ff3b30;
$border-color: #e5e5ea;

.travel-recommend {
    width: 100%;
    padding: 20px 20px 20px 20px;
    background-color: $background-color;
    border-radius: 16px;
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', sans-serif;
    box-sizing: border-box;
    position: relative;
    
    .recommend-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        
        .header-left {
            .recommend-title {
                font-size: 20px;
                font-weight: 600;
                color: $text-primary;
            }
        }
        
        .header-right {
            display: flex;
            align-items: center;
            background-color: rgba($accent-color, 0.1);
            padding: 6px 12px;
            border-radius: 20px;
            
            .date-icon {
                font-size: 14px;
                margin-right: 4px;
            }
            
            .date-text {
                font-size: 14px;
                color: $accent-color;
                font-weight: 500;
            }
        }
    }
    
    // 日期选择器样式
    .date-picker-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .date-picker-container {
            width: 90%;
            max-width: 320px;
            background-color: $card-background;
            border-radius: 12px;
            box-shadow: $card-shadow;
            overflow: hidden;
            
            .date-picker-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 15px 10px;
                border-bottom: 1px solid $border-color;
                
                .date-picker-title {
                    font-size: 16px;
                    font-weight: 600;
                    color: $text-primary;
                }
                
                .date-picker-close {
                    font-size: 24px;
                    color: $text-secondary;
                    line-height: 1;
                    padding: 0 5px;
                }
            }
            
            .date-picker-content {
                padding: 10px 0;
                height: 200px;
                
                .picker-view {
                    width: 100%;
                    height: 200px;
                    
                    .picker-item {
                        line-height: 40px;
                        text-align: center;
                        font-size: 16px;
                    }
                }
            }
            
            .date-picker-footer {
                display: flex;
                border-top: 1px solid $border-color;
                
                .date-picker-btn {
                    flex: 1;
                    text-align: center;
                    padding: 12px 0;
                    font-size: 16px;
                    
                    &.cancel-btn {
                        color: $text-secondary;
                        border-right: 1px solid $border-color;
                    }
                    
                    &.confirm-btn {
                        color: $accent-color;
                        font-weight: 500;
                    }
                }
            }
        }
    }
    
    .loading-state {
        background-color: $card-background;
        border-radius: 12px;
        padding: 30px;
        box-shadow: $card-shadow;
        
        .loading-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            
            .loading-icon {
                font-size: 24px;
                margin-bottom: 12px;
                animation: rotate 1s linear infinite;
            }
            
            .loading-text {
                font-size: 16px;
                color: $text-secondary;
            }
        }
    }
    
    .error-state {
        background-color: $card-background;
        border-radius: 12px;
        padding: 30px;
        box-shadow: $card-shadow;
        
        .error-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            
            .error-icon {
                font-size: 24px;
                margin-bottom: 12px;
            }
            
            .error-text {
                font-size: 16px;
                color: $error-color;
                margin-bottom: 16px;
                text-align: center;
            }
            
            .retry-btn {
                padding: 8px 20px;
                background-color: $accent-color;
                color: white;
                border-radius: 20px;
                font-size: 14px;
                font-weight: 500;
                box-shadow: 0 2px 8px rgba($accent-color, 0.3);
            }
        }
    }
    
    .recommend-content {
        background-color: $card-background;
        border-radius: 12px;
        box-shadow: $card-shadow;
        overflow: hidden;
        
        .content-header {
            padding: 20px;
            border-bottom: 1px solid rgba($text-secondary, 0.1);
            
            .content-title {
                font-size: 18px;
                font-weight: 600;
                color: $text-primary;
                display: block;
                margin-bottom: 4px;
            }
            
            .content-subtitle {
                font-size: 14px;
                color: $text-secondary;
            }
        }
        
        .content-body {
            padding: 20px;
            
            .recommend-text {
                font-size: 16px;
                line-height: 1.6;
                color: $text-primary;
                white-space: pre-line;
            }
            
            .formatted-content {
                .recommendation-title {
                    font-size: 18px;
                    font-weight: 600;
                    color: $text-primary;
                    margin-bottom: 20px;
                    text-align: center;
                    padding: 10px;
                    background-color: rgba($accent-color, 0.05);
                    border-radius: 8px;
                }
                
                .section-title {
                    display: block;
                    font-size: 16px;
                    font-weight: 600;
                    color: $accent-color;
                    margin-bottom: 8px;
                    border-left: 3px solid $accent-color;
                    padding-left: 8px;
                }
                
                .section-content {
                    display: block;
                    font-size: 15px;
                    color: $text-primary;
                    line-height: 1.5;
                    margin-bottom: 16px;
                    padding: 0 5px;
                }
                
                .recommendation-date, 
                .recommendation-weather,
                .recommendation-tips {
                    margin-bottom: 20px;
                    padding: 10px;
                    background-color: rgba($accent-color, 0.02);
                    border-radius: 8px;
                }
                
                .weather-list {
                    display: flex;
                    flex-direction: column;
                    gap: 5px;
                    
                    .weather-item {
                        font-size: 15px;
                        padding: 5px 0;
                    }
                }
                
                .recommendation-schedule {
                    .day-schedule {
                        margin-bottom: 25px;
                        background-color: rgba($accent-color, 0.02);
                        border-radius: 8px;
                        padding: 12px;
                        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
                        
                        .day-title {
                            display: block;
                            font-size: 17px;
                            font-weight: 600;
                            color: $text-primary;
                            background-color: rgba($accent-color, 0.1);
                            padding: 10px 12px;
                            border-radius: 8px;
                            margin-bottom: 15px;
                            text-align: center;
                        }
                        
                        .time-slots {
                            display: flex;
                            flex-direction: column;
                            gap: 15px;
                            padding-left: 12px;
                            margin-top: 15px;
                            
                            .time-slot {
                                display: flex;
                                flex-direction: column;
                                border-left: 2px solid rgba($accent-color, 0.5);
                                padding-left: 15px;
                                position: relative;
                                margin-bottom: 5px;
                                
                                &:before {
                                    content: "";
                                    position: absolute;
                                    left: -6px;
                                    top: 5px;
                                    width: 10px;
                                    height: 10px;
                                    border-radius: 50%;
                                    background-color: $accent-color;
                                    box-shadow: 0 0 0 2px rgba($accent-color, 0.2);
                                }
                                
                                .time-range {
                                    font-size: 15px;
                                    font-weight: 600;
                                    color: $text-primary;
                                    margin-bottom: 8px;
                                    background-color: rgba($accent-color, 0.05);
                                    padding: 4px 8px;
                                    border-radius: 4px;
                                    display: inline-block;
                                }
                                
                                .time-activity {
                                    font-size: 14px;
                                    color: $text-secondary;
                                    line-height: 1.6;
                                    padding: 0 5px;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.action-buttons {
    margin-top: 20rpx;
    display: flex;
    gap: 20rpx;
    padding: 0 20rpx;
    width: 100%;
    box-sizing: border-box;
    
    .regenerate-btn, .save-plan-btn {
        flex: 1;
        min-height: 80rpx;
        padding: 10rpx 20rpx;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        box-sizing: border-box;
        
        &:active {
            transform: scale(0.97);
            opacity: 0.9;
        }
        
        .map-icon, .save-icon {
            font-size: 28rpx;
            margin-right: 8rpx;
        }
        
        .map-text, .save-text {
            font-size: 24rpx;
            font-weight: 600;
            color: white;
            white-space: nowrap;
        }
    }
    
    .regenerate-btn {
        background: linear-gradient(135deg, #2196F3, #1976D2);
        box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
        
        &:active {
            box-shadow: 0 2rpx 8rpx rgba(33, 150, 243, 0.2);
        }
    }
    
    .save-plan-btn {
        background: linear-gradient(135deg, #4CAF50, #388E3C);
        box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
        
        &:active {
            box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.2);
        }
    }
}

// 小屏幕适配
@media screen and (max-width: 375px) {
    .action-buttons {
        margin-top: 16rpx;
        gap: 16rpx;
        padding: 0 16rpx;
        
        .regenerate-btn, .save-plan-btn {
            min-height: 64rpx;
            padding: 8rpx 16rpx;
            
            .map-icon, .save-icon {
                font-size: 24rpx;
                margin-right: 6rpx;
            }
            
            .map-text, .save-text {
                font-size: 22rpx;
            }
        }
    }
}

// 大屏幕适配
@media screen and (min-width: 768px) {
    .action-buttons {
        max-width: 600rpx;
        margin: 30rpx auto;
        gap: 24rpx;
        padding: 0 24rpx;
        
        .regenerate-btn, .save-plan-btn {
            min-height: 88rpx;
            padding: 16rpx 32rpx;
            border-radius: 20rpx;
            
            .map-icon, .save-icon {
                font-size: 32rpx;
                margin-right: 8rpx;
            }
            
            .map-text, .save-text {
                font-size: 28rpx;
            }
        }
    }
}
</style>
